import 'package:json_annotation/json_annotation.dart';

import 'login_response.dart';

part 'user_session.g.dart';

@JsonSerializable()
class UserSession {
  String userId;
  DateTime expiresAt;
  String accessToken;
  String refreshToken;

  UserSession(
      {this.userId, this.expiresAt, this.accessToken, this.refreshToken});

  factory UserSession.fromJson(Map<String, dynamic> json) => _$UserSessionFromJson(json);
  Map<String, dynamic> toJson() => _$UserSessionToJson(this);

  factory UserSession.fromLoginResponse(LoginResponse res) {
    return UserSession(
      userId: res.accessToken.userId,
      expiresAt: res.accessToken.accessTokenExpiresAt,
      accessToken: res.accessToken.accessToken,
      refreshToken: res.accessToken.refreshToken,
    );
  }

  bool isExpired() {
    return DateTime.now()
        .toUtc()
        .isBefore(expiresAt.add(new Duration(minutes: -1)).toUtc());
  }
}
